﻿using System.Linq.Expressions;

namespace Common.Core.Util
{
    /// <summary>
    /// 提供常用的函数
    /// </summary>
    public static class Function
    {
        #region 判断给定字符串是否制定类型有效值，并返回该值
        /// <summary>
        /// 判断判断给定字符串是否是16位整数，并返回该值
        /// </summary>
        /// <param name="src"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static bool IsInt16(string src, out short val)
        {
            src = src.Trim();
            return short.TryParse(src, out val);
        }

        /// <summary>
        /// 判断判断给定字符串是否是整数，并返回该值
        /// </summary>
        /// <param name="src"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static bool IsInt32(string src, out int val)
        {
            src = src.Trim();
            return int.TryParse(src, out val);
        }
        /// <summary>
        /// 判断判断给定字符串是否是日期，并返回该值
        /// </summary>
        /// <param name="src"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static bool IsDateTime(string src, out DateTime val)
        {
            src = src.Trim();
            return DateTime.TryParse(src, out val);
        }
        /// <summary>
        /// 判断判断给定字符串是否是浮点数，并返回该值
        /// </summary>
        /// <param name="src"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        public static bool IsFloat(string src, out double val)
        {
            src = src.Trim();
            return double.TryParse(src, out val);
        }
        #endregion

        #region 其他

        /// <summary>
        /// 反向获取Expressions属性的名称
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expr"></param>
        /// <returns></returns>
        public static string GetExpressionPropertyName<T>(Expression<Func<T, object>> expr)
        {
            var rtn = "";
            if (expr.Body is UnaryExpression)
            {
                rtn = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.Name;
            }
            else if (expr.Body is MemberExpression)
            {
                rtn = ((MemberExpression)expr.Body).Member.Name;
            }
            else if (expr.Body is ParameterExpression)
            {
                rtn = ((ParameterExpression)expr.Body).Type.Name;
            }
            return rtn;
        }

        #endregion
    }
}
